/** 
 * Description: 用户积分管理
 * Date:2012-4-14
 * Author:Along	
*/
package com.community.shopping.service.logic;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.community.shopping.dao.UserScoreDao;
import com.community.shopping.domain.Order;
import com.community.shopping.domain.User;
import com.community.shopping.domain.UserScore;


public class UserScoreManager {
	
	private UserScoreDao userScoreDao;

	/**
	 * @param userScoreDao the userScoreDao to set
	 */
	public void setUserScoreDao(UserScoreDao userScoreDao) {
		this.userScoreDao = userScoreDao;
	}
	private UserManager userManager;
	/**
	 * @param userManager the userManager to set
	 */
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	private SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 生成订单时扣除用户积分的方法
	 * @param user
	 * @param order
	 */
	public void delScore(Order order)
	{
		User user=order.getOrderUser();
		Integer currentScore=user.getScore();
		UserScore userScore=new UserScore();
		userScore.setUserId(user.getId());
		userScore.setOrderId(order.getId());
		userScore.setOrderNo(order.getOrderNo());	
		userScore.setScore(-order.getScore());
		userScore.setScoreResult(currentScore-order.getScore());
		userScore.setCreateDate(format.format(new Date()));
		userScoreDao.save(userScore);
		user.setScore(userScore.getScoreResult());
		userManager.save(user);
	}
	
	/**
	 * 完成订单时给用户增加积分的方法
	 * @param user
	 * @param order
	 */
	public void addScore(Order order)
	{
		User user=order.getOrderUser();
		Integer currentScore=user.getScore();
		Integer priceToScore=(int)(order.getTotalPrice()*10);
		UserScore userScore=new UserScore();
		userScore.setUserId(user.getId());
		userScore.setOrderId(order.getId());
		userScore.setOrderNo(order.getOrderNo());	
		userScore.setScore(priceToScore);
		userScore.setScoreResult(currentScore+priceToScore);
		userScore.setCreateDate(format.format(new Date()));
		userScoreDao.save(userScore);
		user.setScore(userScore.getScoreResult());
		userManager.save(user);		
	}
	
	/**
	 * 根据条件下翻页查询
	*/
	public List getUserScores(String sql,Page page){
		return userScoreDao.getUserScores(sql, page);
	}

}
